package com.mmbang.search;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.Scorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;



//import com.mmbang.entity.TopicEntity;
import com.mmbang.entity.DistrictEntity;
import com.mmbang.util.FileRes;
import com.mmbang.util.StringOperation;
import com.webssky.jcseg.core.Config;
import com.webssky.jcseg.lucence.JcsegAnalyzer;

public class SearchPet implements SearchI{
	
	
	public static String searchFile = FileRes.getPropValue("searchFileForXq");
    //索引文件位置D://test1
    File dataFile = new File(searchFile);
	
	public List search(String keywords) throws IOException, ParseException, InvalidTokenOffsetsException {
		List list = new ArrayList();
		  File file = new File(searchFile);
		  FSDirectory directory = FSDirectory.open(file);
		IndexReader reader = IndexReader.open(directory);
//		Analyzer analyzer = new IKAnalyzer(true);
//		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
//		Analyzer analyzer = new JcsegAnalyzer(Config.COMPLEX_MODE);
		Analyzer analyzer = new JcsegAnalyzer(Config.SIMPLE_MODE);
		
		  //简单索引
		  IndexSearcher searcher = new IndexSearcher(reader);
//		  Term t = new Term("name", "婴儿发烧");
//		  TermQuery query = new TermQuery(t);
		  
			QueryParser qp = new QueryParser(Version.LUCENE_40, "district_name",  analyzer);
			qp.setDefaultOperator(QueryParser.AND_OPERATOR);
//			qp.setDefaultOperator(QueryParser.OR_OPERATOR);
			Query query = qp.parse(keywords);
		  
			
            //关键字高亮
            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
            
            Scorer scorer = new QueryScorer(query);
            Highlighter highlighter = new Highlighter(formatter, scorer);			
			
		     
System.out.println("query:" + query);		     
		     //获得得分靠前的两个匹配记录
		     ScoreDoc[] docs = searcher.search(query, 10).scoreDocs;
System.out.println("docs.length:" + docs.length);     
		     for(int i = 0; i < docs.length; i++) {
		      Date start = new Date();
		      String district_name = searcher.doc(docs[i].doc).get("district_name");
		      System.out.println("district_name:"+district_name);
		      
		      String introduction = searcher.doc(docs[i].doc).get("introduction");
		      String id = searcher.doc(docs[i].doc).get("id");
		      String url = searcher.doc(docs[i].doc).get("url");
		      Date end = new Date();

		      
		      
              float score = docs[i].score;
              
//System.out.println("score:" +score + (score>0.9));
              
          	//得分值

             
//              System.out.println("id:" + id + "      time:" + time +"           title" + title +"      score:" + score);
              
//              name = highlighter.getBestFragment(analyzer, "name", name);
//              
//              if(name == null){
//            	  name = searcher.doc(docs[i].doc).get("name");
//              }
               
//  System.out.println("id:" + id);
//  System.out.println("name:" + name);		      
              /*
		      TopicEntity topicEntity = new TopicEntity();
		      topicEntity.setId(id);
		      topicEntity.setName(name);
		      topicEntity.setUrl(url);
		      topicEntity.setScore(String.valueOf(score));
		      if((score>0.9)) {
			      list.add(topicEntity);		    	  
		      }
		      */
              DistrictEntity districtEntity = new DistrictEntity();
              districtEntity.setId(id);
              districtEntity.setDistrict_name(district_name);
              districtEntity.setIntroduction(introduction);
              

		     }
		     return list;
		  
	}
	
	
	 /**
     * 个人用户中心信息作为文章一起来处理
     * 对搜索返回的前n条结果进行分页显示
     * @param keywords			查询关键词
     * @param pageSize		每页显示记录数
     * @param currentPage		当前页 
     * @param searchType		0为标题精确搜索 1为全文精确搜索 2为标题+全文模糊搜索 3标题模糊搜索
     * @param searchAfterIndex 起始的索引位置
     *
     */
	  	  
	  //修改版本
	  public List search(String keywords,int pageSize,int currentPage,String searchType) {

		  	int searchAfterIndex =0;
		  
		  	List list = new ArrayList();
		  	List returnList_tmp = new ArrayList();
		  	List returnList = new ArrayList();
	        IndexSearcher isearcher = null;
	        Directory directory = null;
	        Analyzer analyzer = new JcsegAnalyzer(Config.SIMPLE_MODE);
	        try {
	            directory = FSDirectory.open(dataFile);
	             
	            //创建索引搜索器 且只读
	            IndexReader reader = IndexReader.open(directory); 
	            isearcher = new IndexSearcher(reader);
//	            isearcher.setSimilarity(new DefaultSimilarity());
//	            isearcher.setSimilarity(new SweetSpotSimilarity());
//	            isearcher.setSimilarity(new BaicaiPositionSimilarity());
	            //可按多个属性排序
	            SortField sortField =new SortField("priority",SortField.Type.INT,true);
	            Sort sort =  new Sort(new SortField[]{SortField.FIELD_SCORE,new SortField(null, SortField.Type.DOC, true)});


				QueryParser qp = new QueryParser(Version.LUCENE_40, "district_name",  analyzer);
				qp.setDefaultOperator(QueryParser.AND_OPERATOR);
//				qp.setDefaultOperator(QueryParser.OR_OPERATOR);
				Query query = qp.parse(keywords);
				
System.out.println("query:" + query);

		
//				boolean searchAuthor = false;

//				TopDocs topDocs = isearcher.search(query, Integer.parseInt(FileRes.getPropValue("pagecountMaxNum")), sort);

//				Vector vecIndex1 = listOperation.getDinstinctCountComplex(topDocs, isearcher, currentPage<=1);
				



				//查询起始记录位置
				int begin = pageSize * (currentPage - 1) ;
				//int begin =0;
				//查询终止记录位置
//				int end = Math.min(begin + pageSize, vecIndex1.size());
				//int end = Math.min(pageSize, distinctCountNum);
System.out.println("begin:" + begin);
//System.out.println("end:" + end);
				
				TopDocs result = isearcher.search(query, Integer.parseInt(FileRes.getPropValue("pagecountMaxNum")));
              ScoreDoc searchAfterscoreDoc=null;
              //若是当前页是第一页面scoreDoc=null。
              if(begin>0){
                  //因为索引是从0开端所以要index-1
              	searchAfterscoreDoc=result.scoreDocs[begin-1];
              }
				
//              ScoreDoc searchAfterscoreDoc = new ScoreDoc(begin-1, (float)100);
				
				TopDocs topDocs = isearcher.searchAfter(searchAfterscoreDoc,query, pageSize);//(query2, Integer.parseInt(FileRes.getPropValue("pagecountMaxNum")));//,sort

	            ScoreDoc[] hits = topDocs.scoreDocs;
	            
		          //搜索结果总数量
	System.out.println("total hits :" + hits.length);
				
				
				
	             
	            //关键字高亮
	            Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
	            
	            Scorer scorer = new QueryScorer(query);
	            Highlighter highlighter = new Highlighter(formatter, scorer);

	            
	            //进行分页查询
	            //for(int i=begin;i<end;i++) {
	            for(ScoreDoc scoreDoc : hits){
//	            for(int i=begin;i<end;i++) {
//	            	ScoreDoc scoreDoc = (ScoreDoc)hits[i];
//System.out.println("scoreDoc.doc:" + scoreDoc.doc);
//	            	int aa =0;
//	            	aa =Integer.parseInt(vecIndex1.get(i).toString());
	                Document hitDoc = isearcher.doc(scoreDoc.doc);
	                
//	            	Document hitDoc = isearcher.doc(Integer.parseInt(vecIndex1.get(i).toString()));
	                
	                String id = hitDoc.get("id");
	                String district_name = hitDoc.get("district_name");
	                String address = hitDoc.get("address");
	                String introduction = hitDoc.get("introduction");
	                String introduction_out = StringOperation.splitAndFilterString(introduction,50);

	                
//Explanation explain = isearcher.explain(query, scoreDoc.doc);

//System.out.println("title:" + title );
//System.out.println("bang_id:" + bang_id );
//System.out.println("title:" + title + ":" + explain.toHtml());
//System.out.println("title:" + title + ":" + explain.toString());

	                //float score = scoreDoc.score;
	            	//得分值

	               
//	                System.out.println("id:" + id + "      time:" + time +"           title" + title +"      score:" + score);
	                
//	                title = highlighter.getBestFragment(analyzer, "title", title);
//	                content = highlighter.getBestFragment(analyzer, "content", content_out);
//	                
//	                if(title == null){
//	                    title = hitDoc.get("title");
//	                }
//	                 
//	                if(content == null){
//	                    content = content_out;
//	                }
      
	                //System.out.println("doc:" + scoreDoc.doc + "    score:" + score + "   id:" + id + "   title:" + title + "    content:" + content);
//	                System.out.println("id:" + id + "      time:" + time +"           title" + title +"      score:" + score);
	                DistrictEntity districtEntity = new DistrictEntity();

	                districtEntity.setId(id);
	                districtEntity.setDistrict_name(district_name);
	                districtEntity.setAddress(address);
	                districtEntity.setIntroduction(introduction_out);
	                list.add(districtEntity); 
	            }
	            //returnList_tmp = listOperation.getDinstinctListComplex(list);
//System.out.println("returnList_tmp.size():" + returnList_tmp.size());	            
	            
//	            for(int i=begin;i<end;i++) {
////System.out.println("i:" + i);	            	
//	            	returnList.add(returnList_tmp.get(i));
//	            }
	            
	        } catch (Exception e) {
	            //throw new RuntimeException(e);
	        	System.out.println(e.getMessage());
	        	list = new ArrayList();
	        	
	        } finally {
	            try {
	               // isearcher.close();
	                directory.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        
	        return list;
//	        return returnList;
	         
	    
	  } 
		
	
	
		/**
	     * 对搜索返回的前n条结果进行分页显示
	     * @param keyWord       查询关键词
	     * @param pageSize      每页显示记录数
	     * @param currentPage   当前页 
	     * @param searchType    0为标题搜索 1为全文搜索 2为标题+全文精确搜索
	     *
	     */
		  public String get_all_json(String keyWord,int pageSize,int currentPage,String searchType)  {
			  String returnJsonValue = "{\"message\": \"\",\"success\":true";
			  
			  
System.out.println("xq_keyWord"+keyWord);			  
			  
			  returnJsonValue += ",\"xq\":" + this.search_get_xq_json(keyWord, pageSize, currentPage, searchType);
			  List list_next_page =search(keyWord,pageSize,currentPage+1,searchType);
			  
			  if(list_next_page.size()>0){
				  
				  returnJsonValue += ",\"is_more\":true";   
			  }else {
				  returnJsonValue += ",\"is_more\":false"; 
			  }
			  
			  returnJsonValue += "}";
			  
			  return returnJsonValue;
		  }
		 	  
			/**
		     * 对搜索返回的前n条结果进行分页显示
		     * @param keyWord       查询关键词
		     * @param pageSize      每页显示记录数
		     * @param currentPage   当前页 
		     * @param searchType    0为标题搜索 1为全文搜索 2为标题+全文精确搜索
		     *
		     */
		    public String search_get_xq_json(String keyWord,int pageSize,int currentPage,String searchType) {
		    	  List list =search(keyWord,pageSize,currentPage,searchType);
		    	  int list_size = list.size();
		    	  
		    	  String returnJsonValue = "[";
		    	  
		    	  for(int i=0;i<list_size;i++) {
		    		DistrictEntity entity = (DistrictEntity)list.get(i);
					String value="{";
					value = value + "\"id\":" +entity.getId()  +",";
					value = value + "\"name\":\"" +StringOperation.splitAndFilterString(entity.getDistrict_name(),50)+"\",";
//					value = value + "\"content\":\"" +StringOperation.splitAndFilterString(String.valueOf(entity.getIntroduction()),50) +"\",";
					value = value + "\"address\":\"" +entity.getAddress()  +"\"";
					value = value + "}";
					if(i==0) {
						returnJsonValue = returnJsonValue + value;
					}else {
						returnJsonValue = returnJsonValue + "," + value;
					}
					 
		    	  }
		    	  returnJsonValue += "]";
		    	  return returnJsonValue;
		      }
		    
		  	  

	/**
	 * @param args
	 * @throws ParseException 
	 * @throws IOException 
	 * @throws InvalidTokenOffsetsException 
	 */
	public static void main(String[] args) throws IOException, ParseException, InvalidTokenOffsetsException {
		// TODO Auto-generated method stub
		SearchPet test = new SearchPet();
//		test.search("怀孕初期吃什么好");
//		test.search("宝宝感冒了怎么办");
//		test.search("宝宝哪里上学比较好");
//		test.search("象");
//		test.search("xiang");
//		test.search("象屿");
//		test.search("象屿郦庭");
		
		
//		List list = test.search("象屿珑庭", 5, 1, "2");
//		for(int i=0;i<list.size();i++) {
//			DistrictEntity districtEntity = (DistrictEntity)list.get(i);
//			System.out.println(districtEntity.getDistrict_name());
//		}
		System.out.println(test.get_all_json("古美", 5, 1, "2"));
		
		
	}

}
